/**
 * 
 */
package uscdb.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import com.alibaba.fastjson.JSON;

/**
 * @author ShaoZhulei
 * 
 */
public class JsonFileCRUD {

	//public static final String BASE_DIRECTORY =System.getProperty("user.dir")+"/src/main/webapp/user";
	public static final String SERVICE_FILE_NAME ="service.json";
//	public static final String BASE_DIRECTORY = "";

	/**
	 * @param <E>
	 * @description 判断集合中是否存在实体
	 * @param e
	 * @param entities
	 * @return
	 */
	public static <E> boolean isExistsJSON(E e, List<E> entities) {
		boolean result = false;
		for (E entity : entities) {
			// System.out.println(e.equals(entity));
			if (e.equals(entity)) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * @description 往.json文件中添加List<Entity>，存在则update
	 * @param en
	 * @param clazz
	 *            Service.class
	 * @param  BASE_DIRECTORY
	 */
	public static <E> void addJSONString(List<E> list, Class<E> clazz, String fileName, String BASE_DIRECTORY) {
		//System.out.print(BASE_DIRECTORY);
		String listString = readJSONString(fileName,BASE_DIRECTORY);
		List<E> entities = JSON.parseArray(listString, clazz);
		for (E e : list) { // 根据id判断是否存在
			if (!isExistsJSON(e, entities)) {// 存在update(先删再加）,不存在add
				entities.add(e);
			} else {
				int pos = entities.indexOf(e);
				entities.remove(pos);
				entities.add(e);
			}
		}
		jsonWriteOut(entities, fileName,BASE_DIRECTORY);
	};

	/**
	 * @description 读取.json文件里的json
	 * @param fileName
	 *            读取的json文件名
	 * @param BASE_DIRECTORY
	 * @return
	 */
	public static String readJSONString(String fileName,String BASE_DIRECTORY) {
		Path file = Paths.get(BASE_DIRECTORY).resolve(fileName);
		if (!Files.exists(file)) {
			System.out.println(file + " does not exist. Terminating program.");
			//System.exit(1);
		}
		String returnArray = "";
		try (BufferedReader fileIn = new BufferedReader(Files.newBufferedReader(file,
				Charset.forName("UTF-8")))) {
			String jsonArray = null;
			while ((jsonArray = fileIn.readLine()) != null) {
				returnArray += jsonArray;
				// System.out.println("readJSONString:" + returnArray);
			}
		} catch (IOException e) {
			System.err.println("Error writing file: " + file);
			e.printStackTrace();
		}
		if (returnArray.length() < 1)
			returnArray = "[]";// 如果是空，就赋值为[]，防止抛出错误。
		return returnArray;
	}

	/**
	 * @description 删除json文件中的 E entity
	 * @param entity
	 * @param clazz
	 * @param BASE_DIRECTORY
	 */
	public static <E> void deleteJSONString(E entity, Class<E> clazz, String fileName,String BASE_DIRECTORY) {
		String listString = readJSONString(fileName,BASE_DIRECTORY);
		List<E> entities = JSON.parseArray(listString, clazz);
		for (E e : entities) {
			// System.out.println("e.equals(entity)__________--->"+ e.equals(entity));
			if (e.equals(entity)) { // 存在则删除
				entities.remove(entity);
				break;
			}
		}
		jsonWriteOut(entities, fileName,BASE_DIRECTORY);
	}

	/**
	 * @description 将list集合写入json文件
	 * @param entities
	 * @param fileName
	 * @param BASE_DIRECTORY
	 */

	private static <E> void jsonWriteOut(List<E> entities, String fileName ,String BASE_DIRECTORY) {
		String arrayString = JSON.toJSONString(entities);// 集合转换成json字符串
		Path file = Paths.get(BASE_DIRECTORY).resolve(fileName);
		//System.out.print(BASE_DIRECTORY);
		//System.out.print(file);
		try {
			// Create parent directory if it doesn't exist
			Files.createDirectories(file.getParent());
		} catch (IOException e) {
			System.err.println("Error creating directory: " + file.getParent());
			e.printStackTrace();
		}
		// Path file = Paths.get(BASE_DIRECTORY).resolve("jsonArray.json");
		try (BufferedWriter fileOut = Files.newBufferedWriter(file,
				Charset.forName("UTF-8"))) {
			fileOut.write(arrayString);
			fileOut.newLine(); // Write separator
			fileOut.flush();
			fileOut.close();
		} catch (IOException e) {
			System.err.println("Error writing file: " + file);
			e.printStackTrace();
		}
	}

	 public static void main(String[] args) {
		 System.out.print(SERVICE_FILE_NAME);
//	 Service service=new Service("江苏", "江苏");
//	 List<Service> services=new ArrayList<Service>();
//	 services.add(service);
//	 Service service1=new Service("山东", "山东");
//	 services.add(service1);
//	 addJSONString(services,Service.class,_FILE_NAME);
	 //deleteJSONString(service, Service.class,_FILE_NAME);
	 }

}
